// 简化版聊天历史持久化工具类，使用localStorage代替Service Worker
import type { MessageType } from './pages/newbot/botaxios';
import { STORAGE_CONFIG } from './config';

// 定义本地存储键名
const CHAT_STORAGE_KEY = STORAGE_CONFIG.CHAT_HISTORY_KEY;
const STYLE_STORAGE_KEY = STORAGE_CONFIG.STYLE_KEY;

// 聊天消息类型 - 与导入的MessageType保持一致
export type Message = MessageType;

class ChatStorageService {
  private messages: MessageType[] = [];
  private readonly STORAGE_KEY = 'companion_chat_history';
  private history: MessageType[] = [];
  private maxHistoryLength = STORAGE_CONFIG.MAX_HISTORY_LENGTH;
  
  constructor() {
    // 初始化时加载历史消息
    this.loadChatHistory().then(msgs => {
      this.messages = msgs;
    });
    this.loadHistory();
  }
  
  // 获取当前内存中的聊天历史
  public getHistory(): MessageType[] {
    return this.messages;
  }
  
  // 添加一条消息并保存
  public addMessage(message: MessageType): void {
    this.messages.push(message);
    this.saveChatHistory(this.messages);
  }
  
  // 保存聊天历史到localStorage
  public async saveChatHistory(messages: MessageType[]): Promise<boolean> {
    try {
      this.messages = messages;
      localStorage.setItem(CHAT_STORAGE_KEY, JSON.stringify(messages));
      return true;
    } catch (error) {
      console.error('保存聊天历史失败:', error);
      return false;
    }
  }

  // 从localStorage加载聊天历史
  public async loadChatHistory(): Promise<MessageType[]> {
    try {
      const storedData = localStorage.getItem(CHAT_STORAGE_KEY);
      if (storedData) {
        return JSON.parse(storedData);
      }
    } catch (error) {
      console.error('加载聊天历史失败:', error);
    }
    return [];
  }

  // 保存风格设置到localStorage
  public async saveStyle(styleType: string): Promise<boolean> {
    try {
      localStorage.setItem(STYLE_STORAGE_KEY, styleType);
      return true;
    } catch (error) {
      console.error('保存风格设置失败:', error);
      return false;
    }
  }

  // 从localStorage加载风格设置
  public async loadStyle(): Promise<string> {
    try {
      const storedStyle = localStorage.getItem(STYLE_STORAGE_KEY);
      return storedStyle || '温柔型'; // 默认风格
    } catch (error) {
      console.error('加载风格设置失败:', error);
      return '温柔型';
    }
  }

  // 检查是否支持localStorage
  public isSupported(): boolean {
    try {
      const testKey = '__test_storage__';
      localStorage.setItem(testKey, testKey);
      localStorage.removeItem(testKey);
      return true;
    } catch (e) {
      return false;
    }
  }

  // 加载历史记录
  private loadHistory(): void {
    try {
      const savedHistory = localStorage.getItem(this.STORAGE_KEY);
      if (savedHistory) {
        this.history = JSON.parse(savedHistory);
      }
    } catch (error) {
      console.error('加载聊天历史失败:', error);
      this.history = [];
    }
  }

  // 保存历史记录
  private saveHistory(): void {
    try {
      localStorage.setItem(this.STORAGE_KEY, JSON.stringify(this.history));
    } catch (error) {
      console.error('保存聊天历史失败:', error);
    }
  }

  // 添加消息
  public addMessageToHistory(message: MessageType): void {
    this.history.push(message);

    // 限制历史记录长度
    if (this.history.length > this.maxHistoryLength) {
      this.history = this.history.slice(this.history.length - this.maxHistoryLength);
    }

    this.saveHistory();
  }

  // 获取历史记录
  public getHistoryFromStorage(): MessageType[] {
    return [...this.history];
  }

  // 获取最近n条消息
  public getRecentMessages(count: number): MessageType[] {
    return this.history.slice(-count);
  }

  // 清空历史记录
  public clearHistory(): void {
    this.history = [];
    this.saveHistory();
  }

  // 设置最大历史记录长度
  public setMaxHistoryLength(length: number): void {
    if (length > 0) {
      this.maxHistoryLength = length;
      
      // 如果当前历史记录超过新的最大长度，则截取
      if (this.history.length > this.maxHistoryLength) {
        this.history = this.history.slice(this.history.length - this.maxHistoryLength);
        this.saveHistory();
      }
    }
  }
}

export const chatStorage = new ChatStorageService(); 